<template>
    <DropZone class="drop-area" @files-dropped="addFiles" #default="{ dropZoneActive }">
        <label for="file-input">
            <b-button id="file-input-btn" variant="outline-primary" @click="file_input_click">Button</b-button>
				<input hidden type="file" id="file-input" multiple @change="onInputChange" />
			</label>
    <ul v-show="files.length">
        <li v-for="file of files" :key="file.id">
            {{ file.file.name }}
            <button @click="removeFile(file);" class="close-icon" aria-label="Remove">×</button>
            <button @click.prevent="uploadFile(file)"  class="upload-button" v-show="file.status == null">Upload</button>
            <span class="status-indicator loading-indicator" v-show="file.status == 'loading'">In Progress</span>
            <span class="status-indicator loading-indicator" v-show="file.status == 'cancelled'">Cancelled</span>
            <span class="status-indicator success-indicator" v-show="file.status == true">Uploaded</span>
            <span class="status-indicator failure-indicator" v-show="file.status == false">Error</span>
            <br>
			<progress max="1" :value.prop="file.uploadPercentage"></progress>
			<br>
        </li></ul>
    <ul class="image-list" v-show="files.length"><FilePreview v-for="file of files" :key="file.id" :file="file" tag="li"/></ul>

    <FileList id = "fileList"></FileList>

    </DropZone>
</template>

<style scoped>

#aaa{
    position: relative;
}
</style>

<script setup>
// template中如果不止一个项并且可能有添加项，把关闭写在单独一行

import FileList from "./components/FileList.vue";
import FilePreview from './components/FilePreview.vue'
import DropZone from './components/DropZone.vue'
import { getCurrentInstance } from 'vue'
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { key } from '../store'
import { inject } from "vue"


const axios = inject('axios');
const store = useStore(key)
const token = store.state.token
const app = getCurrentInstance()
const serverurl = app.appContext.config.globalProperties.$serverurl
// const不要放到async中的formData.append


function file_input_click(){
    let file_input = document.getElementById('file-input')
    file_input.dispatchEvent(new MouseEvent("click"));

}

function onInputChange(e) {
        addFiles(e.target.files)
        e.target.value = null
}


function uploadFile(file) {
    let formData = new FormData()
    const file_ = new File([file.file], encodeURIComponent(file.filename), {type: file.file.type});
    
    formData.append('file', file_)
    formData.append('token', token)
    file.status = 'loading'
    
    axios.post(serverurl + 'upload',
        formData, {
            signal: file.uploadFile_abort.signal,
            headers:{ 'Content-Type': 'multipart/form-data' },
            onUploadProgress: function( progressEvent ) {
                file.uploadPercentage = progressEvent.loaded / progressEvent.total;
            }   
        }).then((response)=>{
            file.status = response.statusText === 'OK';
            file.file_uniquename = response.data.file_uniquename
            console.log(response)
        })
    
}
function uploadFiles(files) {
    return Promise.all(files.map((file) => uploadFile(file)))
}


const files = ref([])

function addFiles(newFiles) {
    let newUploadableFiles = [...newFiles]
        .map((file) => new UploadableFile(file))
        .filter((file) => !fileExists(file.id))
    files.value = files.value.concat(newUploadableFiles)
}

function fileExists(otherId) {
    return files.value.some(({ id }) => id === otherId)
}

function removeFile(file) {
    const index = files.value.indexOf(file)
    if (index > -1) files.value.splice(index, 1)

        let formData = new FormData()
        formData.append('file_uniquename', file.file_uniquename)
        fetch(serverurl + 'upload_del', { method: 'POST', body: formData})
            .then((response) => response.json())
            .then((response_result) => {})
        file.uploadFile_abort.abort()
        file.status = 'cancelled'
        
}


class UploadableFile {
    constructor(file) {
        this.file = file
        this.status = null
        this.file_uniquename = ""
        this.filename = file.name
        this.uploadPercentage = 0
        this.url = URL.createObjectURL(file)
        this.uploadFile_abort = new AbortController();
        this.id = `${file.name}-${file.size}-${file.lastModified}-${file.type}`
    }
}


onMounted(() => {
  
  let formData = new FormData()
  formData.append('token', store.state.token)
  fetch(serverurl + 'validate_token', { method: 'POST', body: formData})
      .then((response) => response.json())
      .then((response_result) => {

          let { result } = response_result
          if (result == true){
              //this.login_failure = true
          } else {
              router.push({path: "/login" });
          }
      })

  })
</script>